//
//  GoodsCollectionViewController.m
//  Yanwei
//
//  Created by 刘文 on 2017/11/30.
//  Copyright © 2017年 DCloud. All rights reserved.
//

#import "GoodsCollectionViewController.h"
#import "MuchUserRequestManager.h"
#import "CollectionBottomView.h"
#import "GoodsCollectionCell.h"
/** #import "NewStoreDetailViewController.h" */
#import "UITableViewRowAction+JZExtension.h"
#import "MJRefresh.h"
#import "ShoppingCartRecommendsView.h"
#import "MuchStoreRequestManager.h"

@interface GoodsCollectionViewController () <UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) UITableView * tableView;
@property (nonatomic, strong) NullStateView *nullStateView;
@property (strong, nonatomic) CollectionBottomView * collectionBottomView;
@property (nonatomic, strong) ShoppingCartRecommendsView *recommendsView;
@property (nonatomic, assign) BOOL hiddenKeepView;

@end

@implementation GoodsCollectionViewController

- (void)_reLayout {
    self.navigationView.title = @"商品收藏";
    
    __weakConfigure
    [self.navigationView addNavigationRightView:CGRectMake(0, 0, 55, 40)
                                      titleFont:APPFONT(14)
                                     titleColor:Color100
                                      titleText:@"编辑"
                                        tapBack:^(UIView *v) {
                                            [__weakSelf rightBaritemAction];
                                        }];
    [self.tableView.mj_header beginRefreshing];
}
- (void)loadDataWithPage {
    /**
    [UserRequestManager userGoodsCollectionWithPage:(int)self.tableView.page sucess:^(NSArray * data) {
        [self.tableView.dataArray addObjectsFromArray:data];
        if (self.tableView.page == 1) {
            [self.tableView.mj_header endRefreshing];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
        
        if (data.count == 0 && self.tableView.page == 1) {
            self.tableView.mj_footer = nil;
            [self loadRecomendsListWithHasCollectData:NO];
        } else {
            if (self.tableView.dataArray.count >= TotalPage) {
                self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                self.tableView.tableFooterView = [UIView new];
            }
        }
        
        if (self.tableView.dataArray.count == 0) {
            self.navigationItem.rightBarButtonItem.customView.hidden = YES;
            self.collectionBottomView.hidden = YES;
        } else {
            self.navigationItem.rightBarButtonItem.customView.hidden = NO;
            self.collectionBottomView.hidden = !self.hiddenKeepView;
        }
        
        self.tableView.page++;
        self.collectionBottomView.selectedAll = NO;
        [self.tableView reloadData];
    } fail:^(NSString *error) {
        [SVProgressHUD showErrorWithStatus:error];
        if (self.tableView.page == 1) {
            [self.tableView.mj_header endRefreshing];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
    }];
     */
}
- (void)loadRecomendsListWithHasCollectData:(BOOL)hasCollectData {
    /**
    [StoreRequestManager storeShopCartRecomendsListWithCart:NO sucess:^(id data) {
        self.tableView.tableFooterView = self.recommendsView;
        // 计算高度
        [self.recommendsView setData:data hasCollectData:hasCollectData];
        [self.tableView reloadData];
    } fail:^(NSString *error) {
        [SVProgressHUD showErrorWithStatus:error];
    }];
     */
}
- (void)rightBaritemAction {
    if (self.tableView.dataArray.count == 0) {
        return;
    }
    _hiddenKeepView = !_hiddenKeepView;
    
    __weakConfigure
    if (!_hiddenKeepView) {
        [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view);
        }];
        
        [self.navigationView addNavigationRightView:CGRectMake(0, 0, 55, 40)
                                          titleFont:APPFONT(14)
                                         titleColor:Color100
                                          titleText:@"编辑"
                                            tapBack:^(UIView *v) {
                                                [__weakSelf rightBaritemAction];
                                            }];
    } else {
        [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.collectionBottomView.mas_top).priorityHigh();
        }];
        
        [self.navigationView addNavigationRightView:CGRectMake(0, 0, 55, 40)
                                          titleFont:APPFONT(14)
                                         titleColor:Color100
                                          titleText:@"完成"
                                            tapBack:^(UIView *v) {
                                                [__weakSelf rightBaritemAction];
                                            }];
        /**
        [self.tableView.dataArray enumerateObjectsUsingBlock:^(GoodsModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.checked) {
                obj.checked = NO;
            }
        }];
         */
        self.collectionBottomView.selectedAll = NO;
    }
    self.collectionBottomView.hidden = !_hiddenKeepView;
    [self.tableView reloadData];
}
/** 删除 */
- (void)deleteAction {
    /**
    if (_hiddenKeepView) {
        NSMutableArray * arr = [[NSMutableArray alloc] init];
        [self.tableView.dataArray enumerateObjectsUsingBlock:^(GoodsModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.checked) {
                [arr addObject:obj.sid];
            }
        }];
        if (arr.count > 0) {
            [SVProgressHUD showWithStatus:@"删除中……" maskType:SVProgressHUDMaskTypeBlack];
            [UserRequestManager userDeleteGoodsCollectionWithCollectIds:arr sucess:^(id data) {
                [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                [self.tableView.mj_header beginRefreshing];
            } fail:^(NSString * error) {
                [SVProgressHUD showErrorWithStatus:error];
            }];
            return;
        } else {
            jxt_showAlertTitle(@"删除内容不能为空");
        }
    }
    
    self.collectionBottomView.hidden = !_hiddenKeepView;
    [self.tableView reloadData];
     */
}
/** 全选 */
- (void)selectAllAction:(BOOL)select {
    /**
    [self.tableView.dataArray enumerateObjectsUsingBlock:^(GoodsModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.checked = select;
    }];
    [self.tableView reloadData];
     */
}
/** 更新全选按钮 */
- (void)updateSelectAllStatus {
    /**
    __block BOOL selectAll = NO;
    [self.tableView.dataArray enumerateObjectsUsingBlock:^(GoodsModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (!obj.checked) {
            selectAll = NO;
            * stop = YES;
        } else {
            selectAll = YES;
        }
    }];
    self.collectionBottomView.selectedAll = selectAll;
     */
}


#pragma mark - <UITableViewDataSource, UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    /**
    if (tableView.dataArray.count != 0) {
        GoodsModel * model = [tableView.dataArray objectAtIndex:indexPath.row];
        if (_hiddenKeepView) {
            model.checked = !model.checked;
            [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            [self updateSelectAllStatus];
        } else {
            NewStoreDetailViewController * vc = [[NewStoreDetailViewController alloc] init];
            vc.goodsModel = model;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
     */
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [tableView.dataArray count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat tableCellHeight = 120;
    return tableCellHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GoodsCollectionCell * cell = [GoodsCollectionCell initTableView:tableView];
    return cell;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(GoodsCollectionCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell.contentView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.tag == 1000) {
            [obj removeFromSuperview];
        }
    }];
    
    /**
    if (tableView.dataArray.count > 0) {
        GoodsModel *model = [tableView.dataArray objectAtIndex:indexPath.row];
        cell.editAction = _hiddenKeepView;
        cell.collectionViewCellModel = model;
    }
     */
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    [self setEditing:false animated:true];
}
- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UIImage * image = [UIImage imageNamed:@"cell_delete"];
    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault image:image handler:^(UITableViewRowAction * _Nullable action, NSIndexPath * _Nullable indexPath) {
        [self deleteRowAction:indexPath];
    }];
    action1.backgroundColor = Color244;
    
    return @[action1];
}


#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 1100
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (@available(iOS 11.0, *)) {
        UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:nil handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
            [self deleteRowAction:indexPath];
            completionHandler(YES);
        }];
        // 也可以设置图片
        deleteAction.image = [UIImage imageNamed:@"cell_delete"];
        UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[deleteAction]];
        return config;
    } else {
        // Fallback on earlier versions
        return nil;
    }
}
#endif


/** 删除cell内容 */
- (void)deleteRowAction:(NSIndexPath *)indexPath {
    /**
    if (self.tableView.dataArray.count != 0) {
        GoodsModel * model = [self.tableView.dataArray objectAtIndex:indexPath.row];
        [UserRequestManager userDeleteGoodsCollectionWithCollectIds:@[model.sid] sucess:^(id data) {
            [self.tableView.mj_header endRefreshing];
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
            [self.tableView.dataArray removeObjectAtIndex:indexPath.row];
            [self.tableView reloadData];
            
            if (self.tableView.dataArray.count == 0) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.tableView.mj_header beginRefreshing];
                });
            }
            
        } fail:^(NSString * error) {
            [self.tableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:error];
        }];
    }
     */
}


#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.delegate = self;
        _tableView.dataArray = [[NSMutableArray alloc] init];
        _tableView.backgroundColor = Color244;
        
        __weakConfigure
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            __weakSelf.tableView.page = 1;
            [__weakSelf.tableView.dataArray removeAllObjects];
            [__weakSelf loadDataWithPage];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [__weakSelf loadDataWithPage];
        }];
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.bottom.and.right.equalTo(self.view);
            make.top.equalTo(self.navigationView.mas_bottom);
        }];
    }
    return _tableView;
}
- (ShoppingCartRecommendsView *)recommendsView {
    if (!_recommendsView) {
        _recommendsView = [[ShoppingCartRecommendsView alloc] init];
        __weakConfigure
        _recommendsView.toGoodsDetailBlock = ^(GoodsModel *model) {
            /**
            NewStoreDetailViewController *newStoreDetailVC = [[NewStoreDetailViewController alloc] init];
            newStoreDetailVC.goodsModel = model;
            newStoreDetailVC.isGroupPurshase = model.groupType == 5;
            [__weakSelf.navigationController pushViewController:newStoreDetailVC animated:YES];
             */
        };
    }
    return _recommendsView;
}
- (NullStateView *)nullStateView {
    if (!_nullStateView) {
        _nullStateView = [[NullStateView alloc] initWithFrame:self.tableView.frame fromViewType:ShopCollectionListEmptyType];
        [self.view addSubview:_nullStateView];
    }
    return _nullStateView;
}
- (CollectionBottomView *)collectionBottomView {
    if (!_collectionBottomView) {
        _collectionBottomView = [[CollectionBottomView alloc] init];
        _collectionBottomView.backgroundColor = [UIColor whiteColor];
        _collectionBottomView.hidden = YES;
        [self.view addSubview:_collectionBottomView];
        [_collectionBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view);
            make.right.equalTo(self.view);
            make.bottom.equalTo(self.view);
            make.height.mas_equalTo(49);
        }];
        
        __weakConfigure
        _collectionBottomView.clickedDeleteActionBlock = ^{
            [__weakSelf deleteAction];
        };
        _collectionBottomView.clickedSelectedActionBlock = ^(BOOL select) {
            [__weakSelf selectAllAction:select];
        };
    }
    return _collectionBottomView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
